package com.sls.game.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.DataConversion;
import com.sls.core.util.PropertiesUtil;
import com.sls.core.util.ServerDateAndTime;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.assist.Helper;
import com.sls.game.common.DeductionRefund;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.DownstreamUserDAO;
import com.sls.game.dao.GoodsOrderDAO;
import com.sls.game.dao.GoodsOrderLogDAO;
import com.sls.game.dao.enfu.EnfuAreaDAO;
import com.sls.game.dao.enfu.EnfuGoodsDAO;
import com.sls.game.dao.enfu.EnfuGoodsDetailDAO;
import com.sls.game.dao.enfu.EnfuServerDAO;
import com.sls.game.page.Pagination;
import com.sls.game.parser.enfu.EnfuBalanceResponse;
import com.sls.game.parser.enfu.EnfuGoodsSynResponse;
import com.sls.game.parser.enfu.EnfuQueryOrderResponse;
import com.sls.game.parser.sls.OrderStatusSendParse;
import com.sls.game.pojo.DeductionRefundInfo;
import com.sls.game.pojo.DownstreamUserInfo;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.GoodsOrderLog;
import com.sls.game.pojo.SLSHttpInterfaceInfo;
import com.sls.game.pojo.enfu.EnfuAreaInfo;
import com.sls.game.pojo.enfu.EnfuBalanceInfo;
import com.sls.game.pojo.enfu.EnfuGoodsDetailInfo;
import com.sls.game.pojo.enfu.EnfuGoodsInfo;
import com.sls.game.pojo.enfu.EnfuOrderStatusInfo;
import com.sls.game.pojo.enfu.EnfuServerInfo;
import com.sls.game.service.EnfuService;
import com.sls.game.supply.deal.EnfuServiceDeal;

/**
 * 
 * @description 恩付--服务接口
 * @author Wangxuegang
 * @date 2013-4-28
 */
@Service("enfuService")
public class EnfuServiceImpl implements EnfuService {
	private static Logger log = Logger.getLogger(EnfuServiceImpl.class);

	private Gson gson = null;

	public EnfuServiceImpl() {
		gson = CommonUtil.gson();
	}

	/**
	 * 网游充值订单表DAO
	 */
	private GoodsOrderDAO goodsOrderDAO;

	private DownstreamUserDAO downstreamUserDAO;

	private GoodsOrderLogDAO goodsOrderLogDAO;

	private EnfuGoodsDAO enfuGoodsDAO;

	@Resource(name = "enfuServerDAO")
	private EnfuServerDAO enfuServerDAO;

	@Resource(name = "enfuAreaDAO")
	private EnfuAreaDAO enfuAreaDAO;

	@Resource(name = "enfuGoodsDetailDAO")
	private EnfuGoodsDetailDAO enfuGoodsDetailDAO;

	public EnfuGoodsDAO getEnfuGoodsDAO() {
		return enfuGoodsDAO;
	}

	@Resource(name = "enfuGoodsDAO")
	public void setEnfuGoodsDAO(EnfuGoodsDAO enfuGoodsDAO) {
		this.enfuGoodsDAO = enfuGoodsDAO;
	}

	public GoodsOrderDAO getGoodsOrderDAO() {
		return goodsOrderDAO;
	}

	@Resource(name = "goodsOrderDAO")
	public void setGoodsOrderDAO(GoodsOrderDAO goodsOrderDAO) {
		this.goodsOrderDAO = goodsOrderDAO;
	}

	public DownstreamUserDAO getDownstreamUserDAO() {
		return downstreamUserDAO;
	}

	@Resource(name = "downstreamUserDAO")
	public void setDownstreamUserDAO(DownstreamUserDAO downstreamUserDAO) {
		this.downstreamUserDAO = downstreamUserDAO;
	}

	public GoodsOrderLogDAO getGoodsOrderLogDAO() {
		return goodsOrderLogDAO;
	}

	@Resource(name = "goodsOrderLogDAO")
	public void setGoodsOrderLogDAO(GoodsOrderLogDAO goodsOrderLogDAO) {
		this.goodsOrderLogDAO = goodsOrderLogDAO;
	}

	/**
	 * 恩付账户余额查询【根据新文档开发】
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryBalance(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuBalanceInfo info = gson.fromJson(body, EnfuBalanceInfo.class);
		boolean flag = checkDataOfBalance(info, head.getRequestId());
		if (flag) {
			try {
				// 签名字符串
				String sign = createSignOfBalance(info);
				if (sign != null && !("".equals(sign))) {
					info.setSign(sign);
				}
				String paraStr = assembleParaOfBalance(info);
				String balanceAddress = PropertiesUtil.getValue(
						"enfu.server.address.queryBalance", "enfu.properties")
						.trim();
				String url = balanceAddress + "?" + paraStr;
				EnfuBalanceInfo enInfo = sendHttpRequestOfBalance(url);
				String resultBody = null;
				if (enInfo != null) {
					resultBody = gson.toJson(enInfo);
				}
				if (log.isInfoEnabled()) {
					log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
				}
				return resultBody;
			} catch (Exception e) {
				log.info("Service处理[" + head.getRequestId() + "]异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}

		return null;
	}

	/**
	 * 
	 * @param url
	 * @return
	 */
	private EnfuBalanceInfo sendHttpRequestOfBalance(String url) {
		EnfuBalanceInfo enInfo = null;
		HttpClient httpClient = new HttpClient();
		try {
			String supplyEncode = "GB2312";
			String xmlStr = httpClient.doGet(url, supplyEncode);
			enInfo = EnfuBalanceResponse.parseBalance(xmlStr);
			return enInfo;
		} catch (Exception e) {
			log.error(e);
		}

		return null;
	}

	/**
	 * 
	 * @param info
	 * @return
	 */
	private String assembleParaOfBalance(EnfuBalanceInfo info) {
		StringBuilder sb = new StringBuilder();
		sb.append("merchantid=");
		sb.append(info.getMerchantid());
		sb.append("&");
		sb.append("sign=");
		sb.append(info.getSign());
		String paraStr = sb.toString().trim();
		return paraStr;
	}

	/**
	 * 
	 * @param info
	 * @param partnerKey
	 * @param supUserKey
	 * @return
	 */
	private String createSignOfBalance(EnfuBalanceInfo info) {
		// 商户号
		String merchantid = info.getMerchantid();
		// 密钥
		String secretKey = PropertiesUtil.getValue("enfu.server.secretKey",
				"enfu.properties").trim();
		StringBuilder sb = new StringBuilder();
		sb.append(merchantid);
		sb.append(secretKey);

		String data = sb.toString();
		String signStr = UtilMD5Encryption.createMD5EncryptionOfGB2312(data);
		if (StringUtils.isEmpty(signStr)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SIGN_ERROR.getCode(),
					ExceptionCodeDes.SIGN_ERROR.getDescription());
		}

		return signStr;
	}

	/**
	 * 
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfBalance(EnfuBalanceInfo info, String reqId) {
		boolean flag = false;
		// 商户号
		String merchantid = info.getMerchantid();
		if ("".equals(merchantid) || merchantid == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_USERNO_NULL.getCode(),
					ExceptionCodeDes.COOPERATION_USERNO_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 合作方 用户编号查询
	 * 
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryMerchantid(Head head) throws ServerDisponseException {
		// 商户号
		String merchantid = PropertiesUtil.getValue("enfu.server.merchantid",
				"enfu.properties").trim();
		EnfuBalanceInfo enfuBalanceInfo = new EnfuBalanceInfo();
		enfuBalanceInfo.setMerchantid(merchantid);
		String resultBody = gson.toJson(enfuBalanceInfo);
		return resultBody;
	}

	/**
	 * 恩付商品插入(新增)
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertEnfuGoods(String body, Head head)
			throws ServerDisponseException {

		return null;
	}

	/**
	 * 同步所有商品详细【根据新文档开发】
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String saveGoodsDetailXML(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		EnfuGoodsDetailInfo info = gson.fromJson(body,
				EnfuGoodsDetailInfo.class);

		final String operator = info.getOperator();
		// 查询原始商品表，获取所有的原始商品编号
		EnfuGoodsInfo enfuGoodsInfo = new EnfuGoodsInfo();
		enfuGoodsInfo.setIsAudit("0"); // 1 已审核 0未审核
		final List<EnfuGoodsInfo> goodsIdlist = enfuGoodsDAO
				.queryAllGoodsId(enfuGoodsInfo);
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (goodsIdlist != null && goodsIdlist.size() > 0) {
					for (EnfuGoodsInfo goodsInfo : goodsIdlist) {
						EnfuServiceDeal.dealGoodsDetail(goodsInfo,
								enfuServerDAO, enfuAreaDAO, enfuGoodsDetailDAO,
								operator);
					}
				}
			}
		}).start();

		return null;
	}

	/**
	 * 商品货源变更
	 * 
	 * @param reqId
	 *            请求ID
	 * @param body
	 *            请求报文body
	 * @return
	 */
	@Override
	public String updateGoodsInfo(String body, Head head)
			throws ServerDisponseException {
		// if (log.isInfoEnabled()) {
		// log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		// }
		// EnfuGoodsInfo info = gson.fromJson(body, EnfuGoodsInfo.class);
		// String partnerId = info.getPartnerId();
		// String serialNumber = info.getSerialNumber();
		// String supProductId = info.getSupProductId();
		// String opCode = info.getOpCode();
		// String unitPrice = info.getUnitPrice();
		// String ts = info.getTs();
		// String sign = info.getSign();
		// boolean flag = checkDataOfUpdate(partnerId, serialNumber,
		// supProductId,
		// opCode, ts, sign, head.getRequestId());
		// if (flag) {
		// EnfuGoodsInfo enfuGoodsInfo = new EnfuGoodsInfo();
		// EnfuGoodsInfo enInfo = null;
		// enInfo = enfuGoodsDAO.queryByGoodsId(supProductId);
		// if ("DELETE".equals(opCode)) { // 删除货源
		// log.info("坚果网络删除商品编号为" + supProductId + "的货源");
		// enfuGoodsInfo.setId(enInfo.getId());
		// enfuGoodsInfo.setPartnerId(partnerId);
		// enfuGoodsInfo.setSupProductId(supProductId);
		// enfuGoodsInfo.setUnitPrice(enInfo.getUnitPrice()); // 删除货源，坚果不传递该参数
		// enfuGoodsInfo.setName(enInfo.getName());
		// enfuGoodsInfo.setProducttype(enInfo.getProducttype());
		// enfuGoodsInfo.setParvalue(enInfo.getParvalue());
		// enfuGoodsInfo.setTs(ts);
		// enfuGoodsInfo.setSign(sign);
		// enfuGoodsInfo.setSerialNumber(serialNumber);
		// enfuGoodsInfo.setOpCode(opCode);
		// enfuGoodsInfo.setGoodsDelete("0"); // "0":该商品删除货源;"1":该商品正常供货
		// enfuGoodsInfo.setIsAudit("0"); // 0：未审核，1已审核
		// try {
		// enfuGoodsDAO.update(enfuGoodsInfo);
		// if (log.isInfoEnabled()) {
		// log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
		// }
		// return null;
		// } catch (Exception e) {
		// log.info("Service处理[" + head.getRequestId()
		// + "]的请求出现数据更新异常！");
		// throw new ServerDisponseException(
		// ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
		// ExceptionCodeDes.ACCESS_DATABASE_ERROR
		// .getDescription());
		// }
		// } else if ("UPDATE".equals(opCode)) { // 更改货源价格
		// if (log.isInfoEnabled()) {
		// log.info("坚果网络更改商品编号为" + supProductId + "的货源价格");
		// }
		// enfuGoodsInfo.setId(enInfo.getId());
		// enfuGoodsInfo.setPartnerId(partnerId);
		// enfuGoodsInfo.setSupProductId(supProductId);
		// if ("".equals(unitPrice) || unitPrice == null) {
		// throw new ServerDisponseException(
		// ExceptionCodeDes.GOODS_SUPPLY_PRICE_NULL.getCode(),
		// ExceptionCodeDes.GOODS_SUPPLY_PRICE_NULL
		// .getDescription());
		// } else {
		// enfuGoodsInfo.setUnitPrice(unitPrice); // 货源更改价格，该参数不能为空
		// }
		//
		// enfuGoodsInfo.setName(enInfo.getName());
		// enfuGoodsInfo.setProducttype(enInfo.getProducttype());
		// enfuGoodsInfo.setParvalue(enInfo.getParvalue());
		// enfuGoodsInfo.setTs(ts);
		// enfuGoodsInfo.setSign(sign);
		// enfuGoodsInfo.setSerialNumber(serialNumber);
		// enfuGoodsInfo.setOpCode(opCode);
		// enfuGoodsInfo.setGoodsDelete("1"); // "0":该商品删除货源;"1":该商品正常供货
		// enfuGoodsInfo.setIsAudit("0"); // 0：未审核，1已审核
		// try {
		// enfuGoodsDAO.update(enfuGoodsInfo);
		// if (log.isInfoEnabled()) {
		// log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
		// }
		// return null;
		// } catch (Exception e) {
		// log.info("Service处理[" + head.getRequestId()
		// + "]的请求出现数据更新异常！");
		// throw new ServerDisponseException(
		// ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
		// ExceptionCodeDes.ACCESS_DATABASE_ERROR
		// .getDescription());
		// }
		// }
		// }
		return null;
	}

	/**
	 * 订单结果查询接口
	 * 
	 * @param body
	 * @param reqId
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String saveQueryOrder(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuOrderStatusInfo info = gson.fromJson(body,
				EnfuOrderStatusInfo.class);
		boolean flag = checkDataOfQueryOrder(info, head.getRequestId());
		if (flag) { // 数据校验通过
			String orderno = info.getOrderno();
			// 商户号
			String merchantid = PropertiesUtil.getValue(
					"enfu.server.merchantid", "enfu.properties").trim();
			// 密钥
			String secretKey = PropertiesUtil.getValue("enfu.server.secretKey",
					"enfu.properties").trim();
			String data = merchantid + orderno + secretKey;
			// 签名字符串
			String sign = UtilMD5Encryption.createMD5EncryptionOfGB2312(data);
			// 请求url
			String url = getOrderStatusUrl(merchantid, orderno, sign);
			EnfuOrderStatusInfo statusInfo = sendMsgOfOrderStatus(url);
			String resultBody = null;
			if (statusInfo != null) {
				resultBody = gson.toJson(statusInfo);
				return resultBody;
			}
		}

		return null;
	}

	/**
	 * 发送订单结果查询消息
	 * 
	 * @param url
	 * @return
	 */
	private EnfuOrderStatusInfo sendMsgOfOrderStatus(String url) {
		HttpClient httpClient = new HttpClient();
		String supplyEncode = "GB2312";
		try {
			log.info("恩付订单查询url：" + url);
			String xmlStr = httpClient.doGet(url, supplyEncode);
			log.info("恩付订单查询响应消息：" + xmlStr);
			EnfuOrderStatusInfo statusInfo = EnfuQueryOrderResponse
					.parseQueryOrder(xmlStr);
			return statusInfo;
		} catch (Exception e) {
			log.error(e);
		}
		return null;
	}

	/**
	 * 获取订单状态查询url
	 * 
	 * @param merchantid
	 * @param orderno
	 * @return
	 */
	private String getOrderStatusUrl(String merchantid, String orderno,
			String sign) {
		// 订单查询地址
		String address = PropertiesUtil.getValue(
				"enfu.server.address.queryOrder", "enfu.properties").trim();
		StringBuilder sb = new StringBuilder();
		sb.append(address);
		sb.append("?");
		sb.append("merchantid=");
		sb.append(merchantid);
		sb.append("&");
		sb.append("orderno=");
		sb.append(orderno);
		sb.append("&");
		sb.append("sign=");
		sb.append(sign);

		String url = sb.toString().trim();
		return url;
	}

	/**
	 * 
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfQueryOrder(EnfuOrderStatusInfo info, String reqId) {
		boolean flag = false;
		// 本地平台订单编号
		String orderno = info.getOrderno();
		if ("".equals(orderno) || orderno == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_PLATFORM_ORDERNO_NULL
							.getCode(),
					ExceptionCodeDes.COOPERATION_PLATFORM_ORDERNO_NULL
							.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 交易订单退款通知接口
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insertRefund(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		EnfuGoodsInfo info = gson.fromJson(body, EnfuGoodsInfo.class);
		if (info == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getDescription());
		}
		boolean flag = checkDataOfRefund(info);
		if (flag) { // 校验通过
			// 更新订单表
			updateGoodsorderRefund(head, info);
		}

		return null;
	}

	/**
	 * 
	 * @param head
	 * @param info
	 */
	private void updateGoodsorderRefund(Head head, EnfuGoodsInfo info) {
		// 合作方平台订单编号
		String ptOrderNo = "";
		// info.getPtOrderNo();
		// SUP平台订单号
		String supOrderNo = "";
		// info.getSupOrderNo();
		// SUP平台退款种类
		String reType = "";
		// info.getReType();
		// 退款金额
		String rePrice = "";
		// info.getRePrice();
		int value = DataConversion.converStringToInteger(rePrice);

		GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
		goodsOrderInfo.setOrderId(ptOrderNo);
		goodsOrderInfo.setSupOrderId(supOrderNo);
		goodsOrderInfo.setReType(reType);
		goodsOrderInfo.setRePrice(value);

		// 数据更新
		try {
			goodsOrderDAO.update(goodsOrderInfo);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		// 写订单日志
		try {
			String orderId = ptOrderNo;
			GoodsOrderInfo goodsOrderInfo1 = new GoodsOrderInfo();
			goodsOrderInfo1 = this.goodsOrderDAO.queryByOrderId(orderId);
			if (goodsOrderInfo1 != null) {
				GoodsOrderLog orderLog = Helper.copy(goodsOrderInfo1);
				orderLog.setId(UUID.randomUUID().toString());
				orderLog.setModifyTime(ServerDateAndTime
						.getNowDateTimeOfFormat());
				this.goodsOrderLogDAO.insert(orderLog);
			}
		} catch (Exception e) {
			log.error(e.toString());
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/**
	 * 
	 * @param info
	 * @return
	 */
	private boolean checkDataOfRefund(EnfuGoodsInfo info) {
		boolean flag = false;
		// 合作平台编号
		String partnerId = "";
		// info.getPartnerId();
		// 合作方平台订单编号
		String ptOrderNo = "";
		// info.getPtOrderNo();
		// SUP平台订单号
		String supOrderNo = "";
		// info.getSupOrderNo();
		// SUP平台退款种类
		String reType = "";
		// info.getReType();
		// 退款金额
		String rePrice = "";
		// info.getRePrice();
		// 签名字符串
		String sign = "";
		// info.getSign();

		if ("".equals(partnerId) || partnerId == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_PLATFORMNO_NULL.getCode(),
					ExceptionCodeDes.COOPERATION_PLATFORMNO_NULL
							.getDescription());
		} else if ("".equals(ptOrderNo) || ptOrderNo == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_PLATFORM_ORDERNO_NULL
							.getCode(),
					ExceptionCodeDes.COOPERATION_PLATFORM_ORDERNO_NULL
							.getDescription());
		} else if ("".equals(supOrderNo) || supOrderNo == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SUP_ORDER_NO_NULL.getCode(),
					ExceptionCodeDes.SUP_ORDER_NO_NULL.getDescription());
		} else if ("".equals(reType) || reType == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.REFUND_TYPE_NULL.getCode(),
					ExceptionCodeDes.REFUND_TYPE_NULL.getDescription());
		} else if ("".equals(rePrice) || rePrice == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.REFUND_AMOUNT_NULL.getCode(),
					ExceptionCodeDes.REFUND_AMOUNT_NULL.getDescription());
		} else if ("".equals(sign) || sign == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SIG_NATURE_NULL.getCode(),
					ExceptionCodeDes.SIG_NATURE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 更新订单记录
	 * 
	 * @param head
	 * @param info
	 * @param userhandleResult
	 */
	private void updateGoodsorder(Head head, EnfuOrderStatusInfo info,
			String userhandleResult, String orderSuccessTime) {
		// 本地平台订单编号
		String ptOrderNo = info.getOrderno();
		// 订单结果
		String status = info.getOrderstatus();
		// SUP平台充值成功时间
		String supOrderSuccessTime = orderSuccessTime;

		GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
		goodsOrderInfo.setOrderId(ptOrderNo);
		goodsOrderInfo.setResult(status);

		String statusValue = "1";
		if ("order_success".equals(status)) { // 成功
			statusValue = "1";
		} else if ("order_failed".equals(status)) { // 失败
			statusValue = "0";
			// 退款操作
			DeductionRefundInfo dedInfo = null;
			dedInfo = DeductionRefund.refundWhenAsynCallBackFailed(ptOrderNo,
					goodsOrderDAO, head);
			String paymentStatus = "";
			if (dedInfo != null) {
				paymentStatus = dedInfo.getPaymentStatus();
			}

			if ("1".equals(paymentStatus)) { // 成功
				goodsOrderInfo.setIsPay("3"); // 退款成功

				// 退款成功，通知下游用户
				DeductionRefund.noticeUserRefundMsg(ptOrderNo, dedInfo,
						goodsOrderDAO, downstreamUserDAO, goodsOrderLogDAO);

			} else if ("2".equals(paymentStatus)) {
				GoodsOrderInfo orderInfo = goodsOrderDAO
						.queryByOrderId(ptOrderNo);
				if (orderInfo != null) {
					String isPayValue = orderInfo.getIsPay(); // 支付状态值
					if ("1".equals(isPayValue)) {
						goodsOrderInfo.setIsPay("2"); // 退款失败
					}
				}
			}
		}
		goodsOrderInfo.setStatus(statusValue);
		goodsOrderInfo.setSupOrderSuccessTime(supOrderSuccessTime);
		goodsOrderInfo.setUserhandleResult(userhandleResult);
		goodsOrderInfo.setSynOrAsy("1");// 异步推送

		// 数据更新
		try {
			goodsOrderDAO.update(goodsOrderInfo);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/**
	 * 创建签名字符串
	 * 
	 * @param ptOrderNo
	 * @param supOrderNo
	 * @param status
	 * @param supOrderSuccessTime
	 * @param failedReason
	 * @param secretKey
	 * @return
	 */
	private String createSign(String ptOrderNo, String supOrderNo,
			String status, String supOrderSuccessTime, String failedReason,
			String secretKey) {
		StringBuilder strBui = new StringBuilder();
		strBui.append(ptOrderNo);
		strBui.append(supOrderNo);
		strBui.append(status);
		if ("ORDER_SUCCESS".equals(status)) { // ---------订单成功，才传成功充值时间
			strBui.append(supOrderSuccessTime);
		} else { // ---------------------订单失败时，才传错误码
			strBui.append(failedReason);
		}
		strBui.append(secretKey);

		String data = strBui.toString().trim();
		String result = null;
		result = UtilMD5Encryption.createMD5Encryption(data);

		return result;
	}

	/**
	 * 恩付商品分页查询
	 * 
	 * @param body
	 * @param reqId
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryByPage(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuGoodsInfo info = gson.fromJson(body, EnfuGoodsInfo.class);
		boolean flag = checkDataOfByPage(info, head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				Pagination<EnfuGoodsInfo> enList = null;
				enList = enfuGoodsDAO.queryPaginationList(info);
				String resultBody = null;
				if (enList != null) {
					resultBody = gson.toJson(enList);
				}
				log.info("分页查询结果为：  " + resultBody);
				if (log.isInfoEnabled()) {
					log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
				}
				return resultBody;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}

		return null;
	}

	/**
	 * 
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfByPage(EnfuGoodsInfo info, String reqId) {
		boolean flag = false;
		String currentPage = info.getCurrentPage() + "";
		String pageSize = info.getPageSize() + "";
		if ("".equals(currentPage) || currentPage == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.CURRENT_PAGE_NULL.getCode(),
					ExceptionCodeDes.CURRENT_PAGE_NULL.getDescription());
		} else if ("".equals(pageSize) || pageSize == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PAGE_SIZE_NULL.getCode(),
					ExceptionCodeDes.PAGE_SIZE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 恩付商品--单条记录查询
	 * 
	 * @param body
	 * @param reqId
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryInfoByGoodsId(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuGoodsInfo info = gson.fromJson(body, EnfuGoodsInfo.class);
		boolean flag = checkDataOfQueryInfoById(info, head.getRequestId());
		if (flag) {
			EnfuGoodsInfo enInfo = null;
			String id = info.getId();
			enInfo = enfuGoodsDAO.queryEnfuGoodsInfoById(id);
			String resultBody = null;
			if (enInfo != null) {
				resultBody = gson.toJson(enInfo);
			}
			return resultBody;
		}
		return null;
	}

	/**
	 * 
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfQueryInfoById(EnfuGoodsInfo info, String reqId) {
		boolean flag = false;
		String id = info.getId();
		if ("".equals(id) || id == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.ID_EMPTY.getCode(),
					ExceptionCodeDes.ID_EMPTY.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 恩付商品批量同步【根据新文档开发】
	 * 
	 * @param body
	 * @param head
	 * @return
	 */
	@Override
	public String saveEnfuGoodsSyn(String body, Head head) {

		EnfuGoodsInfo enfuGoodsInfo = gson.fromJson(body, EnfuGoodsInfo.class);
		String operator = enfuGoodsInfo.getOperator();
		// 访问url
		String url = EnfuServiceDeal.getUrlOfGoodsSyn();
		HttpClient httpClient = new HttpClient();
		String supplyCode = "GB2312";
		try {
			String xmlStr = httpClient.doGet(url, supplyCode);
			List<EnfuGoodsInfo> list = EnfuGoodsSynResponse
					.parseGoodsSyn(xmlStr);
			EnfuServiceDeal.insertGoodsSynInfo(list, enfuGoodsDAO, head,
					operator);
		} catch (Exception e) {
			log.error(e);
		}

		return null;
	}

	/**
	 * 订单状态异步通知
	 * 
	 * @param body
	 * @param head
	 * @return
	 */
	@Override
	public String updateOrderStatus(String body, Head head) {
		EnfuOrderStatusInfo info = gson.fromJson(body,
				EnfuOrderStatusInfo.class);
		boolean flag = checkDataOfUpdateOrderStatus(info);
		if (flag) {
			// 成功处理时间
			String orderSuccessTime = ServerDateAndTime.getNowDateTime().trim();
			// 主动通知下游用户
			String userhandleResult = sendNotifyToDownUserMsg(info, head,
					orderSuccessTime);

			updateGoodsorder(head, info, userhandleResult, orderSuccessTime);
		}
		return null;
	}

	/**
	 * 
	 * @param info
	 * @param head
	 * @param orderSuccessTime
	 * @return
	 */
	private String sendNotifyToDownUserMsg(EnfuOrderStatusInfo info, Head head,
			String orderSuccessTime) {
		String handleResult = "FAILED";
		String orderId = info.getOrderno();
		GoodsOrderInfo orderInfo = goodsOrderDAO.queryByOrderId(orderId);
		String notifyUrl = "";
		// 下游用户编号
		String contractId = null;
		if (orderInfo != null) {
			notifyUrl = orderInfo.getNotifyUrl();
			contractId = orderInfo.getContractId();

			String secretKey = null; // 下游用户密钥
			DownstreamUserInfo downstreamUserInfo = downstreamUserDAO
					.queryUserByUserNO(contractId);
			if (downstreamUserInfo != null) {
				secretKey = downstreamUserInfo.getSecretKey();
			}
			String parameter = assembleParameter(info, orderInfo, secretKey,
					orderSuccessTime);
			String httpUrl = notifyUrl + "?" + parameter;
			HttpClient httpClient = new HttpClient();
			// 供应商返回消息编码方式
			String supplyEncode = "UTF-8";
			// 给下游发消息
			String xmlStr = "";
			try {
				log.info("请求ID：" + head.getRequestId() + "，本地平台异步回调给下游用户的url："
						+ httpUrl);
				xmlStr = httpClient.doGet(httpUrl, supplyEncode);
				log.info("请求ID：" + head.getRequestId() + "，下游用户的返回结果：" + xmlStr);
			} catch (Exception e) {
				log.error("请求ID：" + head.getRequestId() + "，主动通知下游用户出现异常！", e);
			}
			if (xmlStr != null && !("".equals(xmlStr))) {
				SLSHttpInterfaceInfo slsInfo = null;
				slsInfo = OrderStatusSendParse.readUserSendMsg(xmlStr);
				if (slsInfo != null) {
					handleResult = slsInfo.getHandleResult();
				}
			}
		}

		return handleResult;
	}

	/**
	 * 
	 * @param info
	 * @param orderInfo
	 * @param secretKey
	 * @return
	 */
	private String assembleParameter(EnfuOrderStatusInfo info,
			GoodsOrderInfo orderInfo, String secretKey, String orderSuccessTime) {
		// 下游用户订单号
		String ptOrderNo = orderInfo.getMerchantOrderId();
		// 本地订单号
		String supOrderNo = info.getOrderno();
		// 充值后状态
		String orderState = info.getOrderstatus();
		String err_msg = info.getRechargeresult();

		StringBuilder strBui = new StringBuilder();
		strBui.append("ptOrderNo=");
		strBui.append(ptOrderNo);
		strBui.append("&");
		strBui.append("supOrderNo=");
		strBui.append(supOrderNo);
		strBui.append("&");
		strBui.append("status=");
		String status = null;
		if ("order_success".equals(orderState)) { // 成功
			status = "ORDER_SUCCESS";
			err_msg = ""; // ----------成功了为空
		} else { // 失败
			status = "ORDER_FAILED"; // ---------失败
		}
		strBui.append(status);
		strBui.append("&");
		if ("ORDER_SUCCESS".equals(status)) { // ---------订单成功，才传成功充值时间
			strBui.append("supOrderSuccessTime=");
			strBui.append(orderSuccessTime);
			strBui.append("&");
		} else { // ---------------------订单失败时，才传错误码
			strBui.append("failedReason=");
			String fr = "";
			if (StringUtils.isNotBlank(err_msg)) {
				try {
					fr = URLEncoder.encode(err_msg, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					log.error("编码异常", e);
				}
			}
			strBui.append(fr);
			strBui.append("&");
		}

		strBui.append("sign=");
		String sign = createSign(ptOrderNo, supOrderNo, status,
				orderSuccessTime, err_msg, secretKey);
		strBui.append(sign);
		log.info("异步发送给下游用户的订单处理结果    \n 合作方订单编号:" + ptOrderNo + "\n 本地平台订单编号:"
				+ supOrderNo + "\n 订单最终处理结果：" + status + "\n订单处理的时间:"
				+ orderSuccessTime + "\n失败原因：" + err_msg);
		String result = strBui.toString().trim();
		return result;
	}

	/**
	 * 
	 * @param info
	 * @return
	 */
	private boolean checkDataOfUpdateOrderStatus(EnfuOrderStatusInfo info) {
		boolean flag = false;
		if (StringUtils.isEmpty(info.getMerchantid())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_PLATFORMNO_NULL.getCode(),
					ExceptionCodeDes.COOPERATION_PLATFORMNO_NULL
							.getDescription());
		} else if (StringUtils.isEmpty(info.getOrderno())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SLS_ORDERNO_NULL.getCode(),
					ExceptionCodeDes.SLS_ORDERNO_NULL.getDescription());
		} else if (StringUtils.isEmpty(info.getOrderstatus())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.ORDER_STATUS_NULL.getCode(),
					ExceptionCodeDes.ORDER_STATUS_NULL.getDescription());
		} else if (StringUtils.isEmpty(info.getRechargetime())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.TIME_STAMP_NULL.getCode(),
					ExceptionCodeDes.TIME_STAMP_NULL.getDescription());
		} else {
			flag = true;
		}
		return flag;
	}

	/**
	 * 商品详细--分页查询
	 * 
	 * @param body
	 * @param head
	 * @return
	 */
	@Override
	public String queryByPageOfGoodsDetail(String body, Head head) {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuGoodsDetailInfo detailInfo = gson.fromJson(body,
				EnfuGoodsDetailInfo.class);
		EnfuGoodsInfo info = new EnfuGoodsInfo();
		info.setCurrentPage(detailInfo.getCurrentPage());
		info.setPageSize(detailInfo.getPageSize());
		boolean flag = checkDataOfByPage(info, head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				Pagination<EnfuGoodsDetailInfo> enList = null;
				enList = enfuGoodsDetailDAO.queryPaginationList(detailInfo);
				String resultBody = null;
				if (enList != null) {
					resultBody = gson.toJson(enList);
				}
				return resultBody;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}
		return null;
	}

	/**
	 * 商品详细，记录更新
	 * 
	 * @param body
	 * @param head
	 * @return
	 */
	@Override
	public String updateGoodsDetail(String body, Head head) {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuGoodsDetailInfo detailInfo = gson.fromJson(body,
				EnfuGoodsDetailInfo.class);
		try {
			enfuGoodsDetailDAO.updateInfo(detailInfo);
		} catch (Exception e) {
			log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
		return null;
	}

	/**
	 * 商品大区--分页查询
	 * 
	 * @param body
	 * @param head
	 * @return
	 */
	@Override
	public String queryByPageOfArea(String body, Head head) {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuAreaInfo areaInfo = gson.fromJson(body, EnfuAreaInfo.class);
		EnfuGoodsInfo info = new EnfuGoodsInfo();
		info.setCurrentPage(areaInfo.getCurrentPage());
		info.setPageSize(areaInfo.getPageSize());
		boolean flag = checkDataOfByPage(info, head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				Pagination<EnfuAreaInfo> areaList = null;
				areaList = enfuAreaDAO.queryPaginationList(areaInfo);
				String resultBody = null;
				if (areaList != null) {
					resultBody = gson.toJson(areaList);
				}
				return resultBody;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}
		return null;
	}

	/**
	 * 商品小服--分页查询
	 * 
	 * @param body
	 * @param head
	 * @return
	 */
	@Override
	public String queryByPageOfSrv(String body, Head head) {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		EnfuServerInfo srvInfo = gson.fromJson(body, EnfuServerInfo.class);
		EnfuGoodsInfo info = new EnfuGoodsInfo();
		info.setCurrentPage(srvInfo.getCurrentPage());
		info.setPageSize(srvInfo.getPageSize());
		boolean flag = checkDataOfByPage(info, head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				Pagination<EnfuServerInfo> srvList = null;
				srvList = enfuServerDAO.queryPaginationList(srvInfo);
				String resultBody = null;
				if (srvList != null) {
					resultBody = gson.toJson(srvList);
				}
				return resultBody;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}
		return null;
	}

}
